<?php

namespace App\Services\ApplyGoldRecordBatchExamine;

use App\Models\User;
use App\Models\GoldRecord;
use Illuminate\Support\Facades\Redis;
use App\Jobs\ExamineGoldProductPayingJob;
use Rainsens\Dinglog\Facades\Dinglog;
use Carbon\Carbon;
use App\Services\ApplyGoldRecordBatchExamine\ApplyGoldRecordExamine;

class ApplyGoldRecordBatchExamine
{
	protected User $user;

	protected array $unpaidCacheIds = [];

	protected string $examineRecord = '';

	public function __construct(User $user, $unpaidCacheIds,$examineRecord)
	{
		$this->user = $user;
		$this->unpaidCacheIds = $unpaidCacheIds;
		$this->examineRecord = $examineRecord;
	}

	public function examine()
	{
		if (count($this->unpaidCacheIds) <= 0) return;

		foreach ($this->unpaidCacheIds as $cacheId) {
            //$this->user->markRecordPayCachePaying($cacheId);
			$vourcherUserId = Redis::hGet($cacheId,'user_id');
            $vourcherUser = User::find($vourcherUserId);

            if(!$vourcherUser) return;
            //Redis::zRem($vourcherUser->voucherRecordsCacheKey($this->examineRecord), $cacheId);
            app(ApplyGoldRecordExamine::class, [
		    	'user' => $vourcherUser,
		    	'cacheId' => $cacheId
		    ])->apply();	   
          
		}

		 
		$count = Redis::hGet($this->examineRecord,"pending_voucher_num");
		$examineCount = Redis::hGet($this->examineRecord,"examine_voucher_num");
		Dinglog::text("原本数量：".$count);
		$pendingVoucherNum = $count - count($this->unpaidCacheIds);

		Dinglog::text("当前数量：".$pendingVoucherNum);

		$record = GoldRecord::query()->where("cache_id",$this->examineRecord)->first();
		$examineCount = $examineCount + count($this->unpaidCacheIds);

		if( $pendingVoucherNum <= 0){
			$pendingVoucherNum = 0;

			if($record->goldSplits()){
				if($examineCount >= $record->goldSplits()->count()){
					 $this->user->addRecordToFinishedCache($this->examineRecord);
					 $record->update(['finished_at'=>Carbon::now()]);
				}
			}else{

				 $this->user->addRecordToFinishedCache($this->examineRecord);
				  $record->update(['finished_at'=>Carbon::now()]);
			}
           
		}
		
		Redis::hMset($this->examineRecord,["pending_voucher_num"=>$pendingVoucherNum,'examine_voucher_num'=> $examineCount]);

	}
}
